package cn.net.susan.util;


import cn.net.susan.constant.NumberConstant;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 该类的主要作用是从请求头中获取Authorization，解析Authorization中的token
 */
public class TokenUtil {

    private static final String AUTHORIZATION_PREFIX = "Basic";
    private static final String AUTHORIZATION_SEPARATE = "@";
    public TokenUtil(){}

    public static String getTokenForAuthorization(HttpServletRequest request){
        //获取请求头中的Authorization信息
        String authorization = request.getHeader("Authorization");
        //如果authorization中不是有效长度或不包含关键字，则返回null
        if (!StringUtils.hasLength(authorization)
                || !authorization.contains(AUTHORIZATION_PREFIX)
                || !authorization.contains(AUTHORIZATION_SEPARATE)) {
            return null;
        }

        //将authorization以@符号作为关键点分离，如果分离得到的元素不为2，则返回null
        String[] values = authorization.split(AUTHORIZATION_SEPARATE);
        if (values.length != NumberConstant.NUMBER_2) {
            return null;
        }
        return values[1];
    }


}
